const { ccclass, property } = cc._decorator;
import { gameEvents } from "../../constants";

//任务预置体
@ccclass
export default class taskItem extends cc.Component {
    private titleLabel: cc.Label = null; //配方名
    private bg: cc.Node = null; //背景
    private bgColor: cc.Color = null;
    private titleColor: cc.Color = null;

    public id: number = 0;
    public state: number = 0;
    public title: string = "";
    public desc: string = "";
    public isSelected: boolean = false; //是否被选中

    onLoad() {
        this.titleLabel = this.node.getChildByName("titleLabel").getComponent(cc.Label);
        this.bg = this.node.getChildByName("bg");
        this.bgColor = this.bg.color;
        this.titleColor = this.titleLabel.node.color;

        this.onEvents();
    }

    start() {}

    protected onDestroy() {
        this.offEvents();
    }

    private onEvents() {
        this.node.on(cc.Node.EventType.TOUCH_END, this.onClick, this);
    }

    private offEvents() {
        this.node.off(cc.Node.EventType.TOUCH_END, this.onClick, this);
    }

    private onClick() {
        //清除其它选中
        for (let i = 0; i < this.node.parent.children.length; i++) {
            if (this.node.parent.children[i].getComponent(this.constructor.name).isSelected == true) {
                this.node.parent.children[i].getChildByName("bg").color = this.bgColor;
                this.node.parent.children[i].getChildByName("titleLabel").color = this.titleColor;
                this.node.parent.children[i].getComponent(this.constructor.name).isSelected = false;
                break;
            }
        }
        this.bg.color = this.bg.color.fromHEX("#0DFF38");
        this.titleLabel.node.color = this.titleLabel.node.color.fromHEX("#0F00FE");
        this.isSelected = true;

        cc.director.emit(gameEvents.onTaskItemClick.toString(), this.node);
    }

    public init(id: number, state: number, title: string, desc: string) {
        if (this.titleLabel == null) {
            this.titleLabel = this.node.getChildByName("titleLabel").getComponent(cc.Label);
        }

        this.id = id;
        this.state = state;
        this.title = title;
        this.desc = desc;
        this.titleLabel.string = this.title;
    }
}
